<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\shopro\user\User;
use think\exception\PDOException;
use think\Db;
use addons\shopro\model\UserWalletApply as WithDraw;
use app\admin\model\shopro\order\OrderExpress;
use linghuo\v2\Linghuo;


/**
 * 示例接口
 */
class Test extends Api
{

    //'order_list','order_update','withdraw_list','withdraw_update', 'share_user_type_update'
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->orderModel = new \app\admin\model\shopro\order\Order;
        $this->storeModel = new \app\admin\model\shopro\store\Store;
        $this->applyModel = new \app\admin\model\UserWithdraw;
    }

    public function order_list()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $orders = $this->orderModel->withTrashed();
        $list = $orders
            ->with(['user', 'item'])
            ->order('id', 'DESC')
            ->select();

        $list = collection($list)->toArray();
        $items = [];
        foreach ($list as $key => $od) {
            // 处理 未支付订单 的 订单 item status_code 状态
            $list[$key] = $this->orderModel->setOrderItemStatusByOrder($od);

            $items = array_merge($items, $od['item']);
        }

        $store_ids = array_unique(array_column($items, 'store_id'));
        $stores = $this->storeModel->where('id', 'in', $store_ids)->select();
        $stores = collection($stores)->toArray();
        $stores = array_column($stores, null, 'id');

        foreach ($list as $key => $od) {
            foreach ($od['item'] as $k => $it) {
                $list[$key]['item'][$k]['store'] = $stores[$it['store_id']] ?? null;
            }
        }
        return $this->success('操作成功', null, $list);
    }

    public function order_update()
    {
        $id = $this->request->post("order_id"); // ID
        $item_ids = $this->request->post("item_ids"); // itemID
        $express_id = $this->request->post("express_id");//包裹id
        $order = $this->orderModel->payed()->where(['id' => $id])->find();
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order['status'] == 0) {
            $this->error("订单状态不对");
        }
        if ($item_ids == '') {
            $this->error('请选择待发货的商品');
        }
        if ($order->status_code === 'groupon_ing') {
            $this->error('该商品还未拼团成功,暂不能发货');
        }

        // 查询要发货的商品
        if ($item_ids == 'all') {   // 选中所有商品
            $where = [
                'order_id' => $id,
                'dispatch_type' => 'express'        // 必须是物流快递的商品
            ];
        } else {
            $where = [            // 选中分包裹商品
                'order_id' => $id,
                'id' => ['in', $item_ids],
                'dispatch_type' => 'express'
            ];
        }

        // 订单包裹
        $orderExpress = null;
        if ($express_id) {
            // 修改包裹
            $orderExpress = OrderExpress::where('id', $express_id)->find();
            if (!$orderExpress) {
                $this->error('包裹不存在');
            }
        }

        $dispatchWhere[] = \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_NOSEND;
        if ($express_id) {
            // 可以修改已发货的商品
            $dispatchWhere[] = \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_SENDED;
        }
        $where['dispatch_status'] = ['in', $dispatchWhere];

        $item_lists = \app\admin\model\shopro\order\OrderItem::where($where)->select();

        if (!$item_lists) {
            $this->error('没有物流发货的商品');
        }
        $express_name = $this->request->post('express_name', '');
        $express_code = $this->request->post('express_code', '');
        $express_no = $this->request->post('express_no', '');
        if (!$express_name || !$express_code || !$express_no) {
            $this->error('请填写完整发货信息');
        }
        $needSubscribe = true;
        if ($orderExpress && $orderExpress->express_no == $express_no && $orderExpress->express_code == $express_code) {
            // 没有编辑快递信息，不需要重新订阅快递
            $needSubscribe = false;
        }
        $orderExpress = Db::transaction(function () use ($order, $item_lists, $orderExpress, $express_name, $express_code, $express_no) {
            foreach ($item_lists as $key => $item) {
                $order->sendItem($order, $item, [
                    "express_name" => $express_name,
                    "express_code" => $express_code,
                    "express_no" => $express_no,
                    "oper" => '',
                    "oper_type" => 'admin',
                ]);
            }

            if (!$orderExpress) {
                // 添加包裹
                $orderExpress = new OrderExpress();
                $orderExpress->user_id = $order->user_id;
                $orderExpress->order_id = $order->id;
            } else {
                // 查询选择的包裹中未被选中的商品，改为未发货
                \app\admin\model\shopro\order\OrderItem::where('order_id', $order['id'])
                    ->where('id', 'not in', array_column($item_lists, 'id'))
                    ->where('express_no', $orderExpress->express_no)
                    ->where('express_code', $orderExpress->express_code)->update([
                        'express_name' => null,
                        'express_code' => null,
                        'express_no' => null,
                        'dispatch_status' => \app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_NOSEND
                    ]);
            }

            $orderExpress->express_name = $express_name;
            $orderExpress->express_code = $express_code;
            $orderExpress->express_no = $express_no;
            $orderExpress->save();

            // 查询已经没有商品的包裹，并且删除
            OrderExpress::whereNotExists(function ($query) use ($order) {
                $order_table_name = (new OrderExpress())->getQuery()->getTable();
                $table_name = (new \app\admin\model\shopro\order\OrderItem())->getQuery()->getTable();
                $query->table($table_name)->where($table_name . '.express_no=' . $order_table_name . '.express_no')
                    ->where($table_name . '.express_code=' . $order_table_name . '.express_code')
                    ->where('order_id', $order['id']);
            })->where('order_id', $order['id'])->delete();
        });
//        if ($needSubscribe) {
//            $type = 'kdniao';
//            if ($type === 'kdniao') {
//                try {
//                    $expressLib = new \addons\shopro\library\Express();
//                    $expressLib->subscribe([
//                        'express_code' => $express_code,
//                        'express_no' => $express_no
//                    ], $orderExpress, $order);
//                } catch (\Exception $e) {
//                    return $e->getMessage();
//                }
//            }
//        }
        return $this->success('发货成功');
    }

    public function withdraw_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $applys = $this->applyModel;
        $list = $applys
            ->order('id', 'DESC')
            ->select();
        $list = collection($list)->toArray();
        return $this->success('操作成功', null, $list);
    }

    public function withdraw_update($ids)
    {
        $successCount = 0;
        $failedCount = 0;
        $ids = $this->request->post("ids"); // IDs
        $ids = explode(',', $ids);
        $applyList = $this->applyModel->where('id', 'in', $ids)->select();
        if (!$applyList) {
            $this->error('未找到提现申请');
        }
        $operate = $this->request->post('operate');
        $rejectInfo = $this->request->post('rejectInfo');
        foreach ($applyList as $apply) {
            Db::startTrans();
            try {
                if (in_array($apply->auditStatus, [$this->applyModel::Auditstatus_1, $this->applyModel::Auditstatus_2])) {
                    throw \Exception('审核过得不能再审核');
                } elseif ($operate == $this->applyModel::Auditstatus_2 && $rejectInfo) {
                    throw \Exception('请填写审核驳回的原因');
                }
                $linghuo = (new Linghuo)->info();
                if ($linghuo['code'] !== 1) {
                    throw \Exception($linghuo['msg']);
                }
                if (floatval($linghuo['data']['result']['availableFee']) < $apply->money) {
                    throw \Exception('Available amount is less than withdrawal amount');
                }
                $updateParams['auditStatus'] = $operate;
                $updateParams['auditMsg'] = $operate != $this->applyModel::Auditstatus_2 ? '' : $rejectInfo;
                $updateParams['auditTime'] = time();
                $result = $apply->allowField(true)->save($updateParams);
                Db::commit();
                $successCount++;
            } catch (\Exception $e) {
                Db::rollback();
                $failedCount++;
                $lastErrorMessage = $e->getMessage();
            }
        }
        if (count($ids) === 1) {
            if ($successCount) $this->success('操作成功');
            if ($failedCount) $this->error($lastErrorMessage);
        } else {
            $this->success('成功: ' . $successCount . '笔' . ' | 失败: ' . $failedCount . '笔');
        }
    }

    public function share_user_type_update()
    {
        $share_user = new \app\admin\model\share\ShareUser;
        $share_user_list = $share_user->select();
        foreach ($share_user_list as $user) {
            if (!empty($user['score'])) {
                $share_user->where(['id' => $user['id']])->update(['is_order' => 1]);
            }
        }
        return $this->success('操作成功');
    }

}
